#pragma once
#include "Socket.hpp"
#include "InetAddr.hpp"
#include <memory>
#include <unistd.h>
#include <signal.h>
#include <functional>

using namespace std;
using callback_t=std::function<std::string(std::string&)>;
class TcpServer
{
public:
    void handler(shared_ptr<Socket> sockfd, InetAddr client)
    {
        string buffer;
        //怎么保证的读取的是一个完整的字符串?我们可以在Jsonstr的前面，加上一个有效载荷，使得原本的Jsonstr->有效载荷/r/n +Jsonstr/r/n
        while (true)
        {
            ssize_t n = sockfd->Recv(&buffer);
            if (n > 0)
            {
                std::string send_messgae=_cb(buffer);//判断是否是一个完整的报文，然后处理数据这些全部都要交给上层
                if(!send_messgae.empty())
                {
                    continue;
                }
                LOG(LogLevel::INFO) << "获取了一个信息";
                sockfd->Send(buffer);
            }
            else if (n == 0)
            {
                LOG(LogLevel::WARNING) << " quit ";
                break;
            }
            else
            {
                break;
            }
        }
        sockfd->Close();
    }

public:
     TcpServer(int port,callback_t cb)
    :   _port(port),
        _listensocket(std::make_unique<TcpSocket>()),
        _cb(cb)
    {
        _listensocket->BuildListenSocketMethod(_port);
    }
    void run()
    {
        while (true)
        {
            InetAddr client;
            auto sockfd = _listensocket->Accept(&client);
            if (sockfd == nullptr)
                continue;
            LOG(LogLevel::DEBUG) << "获取一个新连接: " << client.ToString()
                                 << ", sockfd : " << sockfd->SockFd();
            if (fork() == 0)
            {
                _listensocket->Close();
                // 子进程
                handler(sockfd, client);
                break;
            }
            sockfd->Close();
        }
    }

    ~TcpServer()
    {

    }

private:
    shared_ptr<Socket> _listensocket;
    uint16_t _port;
    callback_t _cb;
};
